
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.Iterator;
import javax.swing.JOptionPane;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * TimetableGeneratorInterface.java
 *
 * Created on 20-Mar-2012, 12:22:49
 */

/**
 *
 * @author matrosj0
 */
public class TimetableGeneratorInterface extends javax.swing.JFrame {

    private ArrayList<ArrayList<DriverShift>> timetable;
    private Calendar startDay;
    
    private int driverIDSelected;
    private int busIDSelected;

    /** Creates new form TimetableGeneratorInterface */
    public TimetableGeneratorInterface(Calendar startDay,
                            ArrayList<ArrayList<DriverShift>> timetable) {
        this.timetable = timetable;
        this.startDay = startDay;
        System.out.println(startDay.get(Calendar.DATE));
        initComponents();
        generateData();
    }

    /**
     * Method used by insertValuesIntoDB()
     * @param day
     * @param service
     * @param bus
     * @param driver
     * @param startTime
     * @param endTime
     */
    
    private void setTimetableLine(Calendar day, int service, int bus, int driver,
            Calendar startTime, Calendar endTime)
    {
        Object[][] fields = new Object[6][2];
        fields[0][0] = "day";
        fields[1][0] = "service";
        fields[2][0] = "bus";
        fields[3][0] = "driver";
        fields[4][0] = "start_time";
        fields[5][0] = "end_time";

        fields[0][1] = day.getTime();
        fields[1][1] = service;
        fields[2][1] = bus;
        fields[3][1] = driver;
        fields[4][1] = startTime.getTime();
        fields[5][1] = endTime.getTime();        
        
        database.busDatabase.new_record("timetable", fields);
    }
    /**
     * Method, that is called, when a controller press "Approve" button. This method
     * updates the 'timetable' table
     */
    private void insertValuesIntoDB()
    {
        //We need to iterate through every day
        Calendar currentDate = (Calendar) this.startDay.clone();
        Calendar endDate = (Calendar) this.startDay.clone();
        endDate.add(Calendar.DAY_OF_MONTH, 7);

        //The index used to get the timetable
        int index = 0;

        // list for storing all drivers, assigned this wekk
        HashSet<Driver> driversAffected = new HashSet<Driver>();
        
        while (currentDate.before(endDate))
        {
            //Get all info for each day
            ArrayList<DriverShift> shiftsToday = timetable.get(index);

            //For each shift
            Iterator<DriverShift> shiftIter = shiftsToday.iterator();

            while (shiftIter.hasNext())
            {
                DriverShift currentShift = shiftIter.next();
                Driver driver = currentShift.getDriver();
                driversAffected.add(driver);
                int driverID = driver.getDriverID();
                int serviceID = currentShift.getService().getServiceID();
                int busID = currentShift.getBusShift().getBus().getBusID();
                Calendar startTime = currentShift.getStartTime();
                Calendar endTime = currentShift.getEndTime();

                setTimetableLine(currentDate, serviceID, busID, driverID, startTime, endTime);
            }

            //Increment day by 1
            currentDate.add(Calendar.DAY_OF_MONTH, 1);
            //Increment index
            index++;
        }

        // Update hours worked this year and week for each driver
        Iterator<Driver> iter = driversAffected.iterator();
        while(iter.hasNext())
        {
            Driver current = iter.next();
            int hoursWeek = Driver.driverInfo.getMinutesWeek(current) / 60;
            int hoursYear = Driver.driverInfo.getMinutesYear(current) / 60;
            DriverInfo.setHoursThisWeek(current.getDriverID(), hoursWeek);
            DriverInfo.setHoursThisYear(current.getDriverID(), hoursYear);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        ApproveButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        textArea = new javax.swing.JTextArea();
        viewSingleDriver = new javax.swing.JButton();
        viewTimetableButton = new javax.swing.JButton();
        viewBusButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Roster Display");
        setName("Timetable"); // NOI18N

        ApproveButton.setText("Approve");
        ApproveButton.setToolTipText("Approve the timetable by writing it to the database");
        ApproveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ApproveButtonActionPerformed(evt);
            }
        });

        cancelButton.setText("Cancel");
        cancelButton.setToolTipText("Cancel the timetable (all data will be lost)");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        textArea.setColumns(20);
        textArea.setRows(5);
        textArea.setDisabledTextColor(new java.awt.Color(1, 1, 1));
        textArea.setEnabled(false);
        jScrollPane2.setViewportView(textArea);

        viewSingleDriver.setText("View a single driver");
        viewSingleDriver.setToolTipText("View the timetable for a single driver ID");
        viewSingleDriver.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                viewSingleDriverActionPerformed(evt);
            }
        });

        viewTimetableButton.setText("View Timetable");
        viewTimetableButton.setToolTipText("View the full timetable");
        viewTimetableButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                viewTimetableButtonActionPerformed(evt);
            }
        });

        viewBusButton.setText("View a single Bus");
        viewBusButton.setToolTipText("View the timetable for a single Bus ID");
        viewBusButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                viewBusButtonActionPerformed(evt);
            }
        });

        jLabel1.setText("For week beginning: " + Service.calendarToDateString(this.startDay));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 465, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(12, 12, 12)
                        .addComponent(ApproveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(16, 16, 16)
                        .addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(viewTimetableButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(viewSingleDriver, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(viewBusButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE)))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 533, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 410, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(ApproveButton)
                        .addComponent(cancelButton))
                    .addComponent(viewBusButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(viewSingleDriver)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(viewTimetableButton)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void ApproveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ApproveButtonActionPerformed
        insertValuesIntoDB();
    }//GEN-LAST:event_ApproveButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        //Close the interface
        int result = JOptionPane.showConfirmDialog(this, "Are you sure?", "Confirmation", JOptionPane.YES_NO_OPTION);

        if (result == 0)
            this.dispose();

    }//GEN-LAST:event_cancelButtonActionPerformed

    private void viewSingleDriverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewSingleDriverActionPerformed

        String resultString = JOptionPane.showInputDialog("Enter driver ID");

        if (resultString != null)
        {
            this.driverIDSelected = Integer.parseInt(resultString);

            viewSingleDriver();
        }

    }//GEN-LAST:event_viewSingleDriverActionPerformed

    private void viewTimetableButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewTimetableButtonActionPerformed

        generateData();
    }//GEN-LAST:event_viewTimetableButtonActionPerformed

    private void viewBusButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewBusButtonActionPerformed

        String resultString = JOptionPane.showInputDialog("Enter bus ID");

        if (resultString != null)
        {
            this.busIDSelected = Integer.parseInt(resultString);

            viewSingleBus();
        }
    }//GEN-LAST:event_viewBusButtonActionPerformed

    private void viewSingleBus()
    {
        //Remove all text from the text area
        textArea.setText("");
        textArea.append("-----------------FOR BUS ID: " + Integer.toString(this.busIDSelected) + " ------------------\n");
        //Set start date
        Calendar currentDate = (Calendar) this.startDay.clone();
        //End date
        Calendar endDate = (Calendar) currentDate.clone();
        endDate.add(Calendar.DAY_OF_MONTH, 7);

        //Index used to get the timetable
        int index = 0;

        while (currentDate.before(endDate))
        {
            //Get all info for each day
            ArrayList<DriverShift> shiftsToday = timetable.get(index);

            //For each shift
            Iterator<DriverShift> shiftIter = shiftsToday.iterator();

            textArea.append("\n\nDay: " + Service.dayToString(currentDate)
                    + "\n\n-------------------------------------------------------------------\n");

            while (shiftIter.hasNext())
            {
                DriverShift currentShift = shiftIter.next();
                                    int busID = currentShift.getBusShift().getBus().getBusID();

                if (busID == this.busIDSelected)
                {
                    int driverID = currentShift.getDriver().getDriverID();
                    int serviceID = currentShift.getService().getServiceID();
                    String fleetNumber = currentShift.getBusShift().getBus().getFleetNumber();
                    String driverName = currentShift.getDriver().getName();
                    Calendar startTime = currentShift.getStartTime();
                    Calendar endTime = currentShift.getEndTime();
                    String areaStart = currentShift.getService().getBusStops().get(0).getAreaName();
                    String areaEnd = currentShift.getService().getBusStops().get(currentShift.getService().getBusStops().size() - 1).getAreaName();

                    textArea.append("Driver: " + driverName);
                    textArea.append("(" + Integer.toString(driverID) + ")");
                    textArea.append(" Bus ID:" + Integer.toString(busID));
                    textArea.append(" Fleet number: " + fleetNumber);
                    textArea.append("\nService ID: " + Integer.toString(serviceID));
                    textArea.append(" " + areaStart + "@" + Service.calendarToString(startTime));
                    textArea.append(" -- " + areaEnd + "@" + Service.calendarToString(endTime));

                    textArea.append("\n\n");
                }
            }

            currentDate.add(Calendar.DAY_OF_MONTH, 1);
            index++;
        }
    }

    private void viewSingleDriver()
    {
        //Remove all text from the text area
        textArea.setText("");
        textArea.append("-----------------FOR DRIVER ID: " + Integer.toString(this.driverIDSelected) + " ------------------\n");
        //Set start date
        Calendar currentDate = (Calendar) this.startDay.clone();
        //End date
        Calendar endDate = (Calendar) currentDate.clone();
        endDate.add(Calendar.DAY_OF_MONTH, 7);

        //Index used to get the timetable
        int index = 0;

        while (currentDate.before(endDate))
        {
            //Get all info for each day
            ArrayList<DriverShift> shiftsToday = timetable.get(index);

            //For each shift
            Iterator<DriverShift> shiftIter = shiftsToday.iterator();

            textArea.append("\n\nDay: " + Service.dayToString(currentDate) + "\n\n-------------------------------------------------------------------\n");

            while (shiftIter.hasNext())
            {
                DriverShift currentShift = shiftIter.next();
                int driverID = currentShift.getDriver().getDriverID();

                if (driverID == this.driverIDSelected)
                {
                    int serviceID = currentShift.getService().getServiceID();
                    String fleetNumber = currentShift.getBusShift().getBus().getFleetNumber();
                    int busID = currentShift.getBusShift().getBus().getBusID();
                    String driverName = currentShift.getDriver().getName();
                    Calendar startTime = currentShift.getStartTime();
                    Calendar endTime = currentShift.getEndTime();
                    String areaStart = currentShift.getService().getBusStops().get(0).getAreaName();
                    String areaEnd = currentShift.getService().getBusStops().get(currentShift.getService().getBusStops().size() - 1).getAreaName();

                    textArea.append("Driver: " + driverName);
                    textArea.append("(" + Integer.toString(driverID) + ")");
                    textArea.append(" Bus ID:" + Integer.toString(busID));
                    textArea.append(" Fleet number: " + fleetNumber);
                    textArea.append("\nService ID: " + Integer.toString(serviceID));
                    textArea.append(" " + areaStart + "@" + Service.calendarToString(startTime));
                    textArea.append(" -- " + areaEnd + "@" + Service.calendarToString(endTime));

                    textArea.append("\n\n");
                }
            }

            currentDate.add(Calendar.DAY_OF_MONTH, 1);
            index++;
        }
    }

    private void generateData()
    {
        //Set text area to empty
        textArea.setText("");
        textArea.append("--------------FULL TIMETABLE-------------\n");
        //We need to iterate through every day
        Calendar currentDate = (Calendar) this.startDay.clone();
        Calendar endDate = (Calendar) this.startDay.clone();
        endDate.add(Calendar.DAY_OF_MONTH, 7);

        //The index used to get the timetable
        int index = 0;




        while (currentDate.before(endDate))
        {
            //Get all info for each day
            ArrayList<DriverShift> shiftsToday = timetable.get(index);

            //For each shift
            Iterator<DriverShift> shiftIter = shiftsToday.iterator();

            textArea.append("\n\nDay: " + Service.dayToString(currentDate) + "\n\n-------------------------------------------------------------------\n");
            while (shiftIter.hasNext())
            {
                DriverShift currentShift = shiftIter.next();
                int driverID = currentShift.getDriver().getDriverID();
                int serviceID = currentShift.getService().getServiceID();
                String fleetNumber = currentShift.getBusShift().getBus().getFleetNumber();
                int busID = currentShift.getBusShift().getBus().getBusID();
                String driverName = currentShift.getDriver().getName();
                Calendar startTime = currentShift.getStartTime();
                Calendar endTime = currentShift.getEndTime();
                String areaStart = currentShift.getService().getBusStops().get(0).getAreaName();
                String areaEnd = currentShift.getService().getBusStops().get(currentShift.getService().getBusStops().size() - 1).getAreaName();

                textArea.append("Driver: " + driverName);
                textArea.append("(" + Integer.toString(driverID) + ")");
                textArea.append(" Bus ID:" + Integer.toString(busID));
                textArea.append(" Fleet number: " + fleetNumber);
                textArea.append("\nService ID: " + Integer.toString(serviceID));
                textArea.append(" " + areaStart + "@" + Service.calendarToString(startTime));
                textArea.append(" -- " + areaEnd + "@" + Service.calendarToString(endTime));

                textArea.append("\n\n");


            }

            //Increment day by 1
            currentDate.add(Calendar.DAY_OF_MONTH, 1);
            //Increment index
            index++;
        }
    }

    /*public void dispose()
    {
        database.busDatabase.close();
        System.out.println("Database closed.    .   .");
        super.dispose();
    }*/
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        database.openBusDatabase();
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                ArrayList<ArrayList<DriverShift>> shifts;
                Roster r = new Roster();
                Calendar start = r.getStartDate();
                shifts = r.generateRoster();
                new TimetableGeneratorInterface(start, shifts).setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton ApproveButton;
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextArea textArea;
    private javax.swing.JButton viewBusButton;
    private javax.swing.JButton viewSingleDriver;
    private javax.swing.JButton viewTimetableButton;
    // End of variables declaration//GEN-END:variables

}
